package com.module.user.ui.feedback

import android.content.Intent
import android.graphics.Typeface
import android.util.Log
import android.view.View
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.SimpleItemAnimator
import com.common.app.base.AppPictureSelectionActivity
import com.common.app.utls.HeadTitleUtils
import com.common.base.utils.*
import com.module.user.R
import com.common.app.adapter.GridImageAdapter
import com.common.app.listener.MyExternalPreviewEventListener
import com.common.app.utls.pictureselect.GlideEngine
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.startActivity
import com.common.base.app.extras.yes
import com.common.base.manager.FullyGridLayoutManager
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureMimeType
import com.luck.picture.lib.decoration.GridSpacingItemDecoration
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.language.LanguageConfig
import com.luck.picture.lib.utils.DensityUtil
import com.luck.picture.lib.utils.MediaUtils
import com.module.user.databinding.UserActivityProblemFeedbackBinding
import com.module.user.ui.feedbackHistory.FeedbackHistoryActivity
import java.io.File

/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/10/1
 * <p>
 * 描述：问题反馈页页面
 * <p>
 * 修订历史：
 */
class ProblemFeedbackActivity : AppPictureSelectionActivity<UserActivityProblemFeedbackBinding, ProblemFeedbackViewModel>(),
    View.OnClickListener {

    override fun getViewModel() = ProblemFeedbackViewModel::class.java

    override fun getViewContentBinding() = UserActivityProblemFeedbackBinding.inflate(layoutInflater)

    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true

    private var launcherResult: ActivityResultLauncher<Intent?>? = null
    private var maxSelectNum = 6
    private val mData: List<LocalMedia> = ArrayList()
    private val mAdapter by lazy { GridImageAdapter(this, mData) }
    private val multipleMode = true//选图是否使用单选模式流程

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, true)

        val headTitleUtils = HeadTitleUtils(this)
        headTitleUtils.setTitle(resources.getString(R.string.user_pr_feedback_title))
        headTitleUtils.setLineStyle(10)

        mViewContentBinding.hrv.isNestedScrollingEnabled = false
        val manager = FullyGridLayoutManager(
            this,
            3, GridLayoutManager.VERTICAL, false
        )
        mViewContentBinding.hrv.layoutManager = manager
        val itemAnimator: RecyclerView.ItemAnimator? = mViewContentBinding.hrv.getItemAnimator()
        (itemAnimator as SimpleItemAnimator).supportsChangeAnimations = false
        mViewContentBinding.hrv.addItemDecoration(
            GridSpacingItemDecoration(
                3,
                DensityUtil.dip2px(this, 8f), false
            )
        )
        mAdapter.selectMax = maxSelectNum
        mViewContentBinding.hrv.adapter = mAdapter

        // 注册需要写在onCreate或Fragment onAttach里，否则会报java.lang.IllegalStateException异常
        launcherResult = createActivityResultLauncher()

        initPictureStyle()

    }

    override fun onResume() {
        super.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    override fun initEvents() {
        super.initEvents()

        mAdapter.setOnItemClickListener(object : GridImageAdapter.OnItemClickListener {
            override fun onItemClick(v: View?, position: Int) {
                // 预览图片、视频、音频
                PictureSelector.create(this@ProblemFeedbackActivity)
                    .openPreview()
                    .setImageEngine(GlideEngine.createGlideEngine())
                    .setSelectorUIStyle(selectorStyle)
                    .setLanguage(LanguageConfig.UNKNOWN_LANGUAGE)
                    .isPreviewFullScreenMode(true)
                    .setExternalPreviewEventListener(MyExternalPreviewEventListener(mAdapter))
                    .startActivityPreview(position, true, mAdapter.data)
            }

            override fun openPicture() {
                freeStyleCropEnabled = true
                aspect_ratio_x = 1f
                aspect_ratio_y = 1.6f
                selectFromAlbum(multipleMode, launcherResult, maxSelectNum - mAdapter.data.size)
            }

            override fun deletePicture(temp: String?) {
//                OBSManager.getInstance().deleteFile(temp);
            }
        })

        mViewContentBinding.tvHistory.setOnClickListener(onClick = this)
        mViewContentBinding.tvSaveBtn.setOnClickListener(onClick = this)
    }

    override fun lazyInitData() {
        super.lazyInitData()

        SpanUtils.create()
            .addSection(getString(R.string.user_pr_feedback_failure_situation_hint))
            .addForeColorSection(getString(R.string.user_pr_feedback_failure_situation_hint2), ViewUtils.getColor(R.color.product_color))
            .showIn(mViewContentBinding.tvFeedbackFailureHint)

    }

    override fun onClick(v: View?) {
        when (v) {
            mViewContentBinding.tvHistory -> {
                startActivity<FeedbackHistoryActivity>(false)
            }
            mViewContentBinding.tvSaveBtn -> {
                requestSubmitFeedback()
            }
        }
    }


    /**
     * 创建一个ActivityResultLauncher
     *
     * @return
     */
    private fun createActivityResultLauncher(): ActivityResultLauncher<Intent?> {
        return registerForActivityResult(
            ActivityResultContracts.StartActivityForResult()
        ) { result ->
            val resultCode = result.resultCode
            if (resultCode == RESULT_OK) {
                val selectList = PictureSelector.obtainSelectorList(result.data)
                analyticalSelectResults(selectList)
            } else if (resultCode == RESULT_CANCELED) {
                Log.i(TAG, "onActivityResult PictureSelector Cancel")
            }
        }
    }


    /**
     * 处理选择结果
     *
     * @param result
     */
    private fun analyticalSelectResults(result: ArrayList<LocalMedia>) {
        for (media in result) {
            if (media.width == 0 || media.height == 0) {
                if (PictureMimeType.isHasImage(media.mimeType)) {
                    val imageExtraInfo = MediaUtils.getImageSize(this, media.path)
                    media.width = imageExtraInfo.width
                    media.height = imageExtraInfo.height
                } else if (PictureMimeType.isHasVideo(media.mimeType)) {
                    val videoExtraInfo = MediaUtils.getVideoSize(this, media.path)
                    media.width = videoExtraInfo.width
                    media.height = videoExtraInfo.height
                }
            }
            Log.i(TAG, "文件名: " + media.fileName)
            Log.i(TAG, "是否压缩:" + media.isCompressed)
            Log.i(TAG, "压缩:" + media.compressPath)
            Log.i(TAG, "初始路径:" + media.path)
            Log.i(TAG, "绝对路径:" + media.realPath)
            Log.i(TAG, "是否裁剪:" + media.isCut)
            Log.i(TAG, "裁剪:" + media.cutPath)
            Log.i(TAG, "是否开启原图:" + media.isOriginal)
            Log.i(TAG, "原图路径:" + media.originalPath)
            Log.i(TAG, "沙盒路径:" + media.sandboxPath)
            Log.i(TAG, "水印路径:" + media.watermarkPath)
            Log.i(TAG, "视频缩略图:" + media.videoThumbnailPath)
            Log.i(TAG, "原始宽高: " + media.width + "x" + media.height)
            Log.i(TAG, "裁剪宽高: " + media.cropImageWidth + "x" + media.cropImageHeight)
            Log.i(TAG, "文件大小: " + media.size)
        }

        uploadImage(result)

    }


    //开始上传图片
    private fun uploadImage(result: ArrayList<LocalMedia>) {
        val imgFile = File(result[0].sandboxPath)
        if (imgFile.exists()) {
            showDialogLoading()
            mViewModel.uploadImage(imgFile,"image").observe(this) {

                dismissLoadingDialog()
                LogUtils.e("===>${it}")
                it.isSuccess().yes {

                    it.Data?.url?.let { urlIt->
                        val isMaxSize = 1 == mAdapter.selectMax
                        val oldSize: Int = mAdapter.data.size
                        result[0].customData = urlIt
                        mAdapter.notifyItemRangeRemoved(0, if (isMaxSize) oldSize + 1 else oldSize)
                        mAdapter.data.add(result[0])
                        mAdapter.notifyItemRangeInserted(0, 1)
                    }
                }

            }
        }
    }

    private fun requestSubmitFeedback() {
        val imgFile = File("sandboxPath")
        if (imgFile.exists()) {
            showDialogLoading()
            mViewModel.requestSubmitFeedback().observe(this) {
                dismissLoadingDialog()
                it.isSuccess().yes {
                }
            }
        }
    }
}